import java.util.HashMap;
import java.util.Map;

/**
 * 力扣1171:从链表中删去总和为0的节点
 */

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class removeZeroSumSublists {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        ListNode head4 = new ListNode(-3);
        ListNode head5 = new ListNode(4);
        head.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        System.out.println(removeZeroSumSublists(head).toString());

    }
    public static ListNode removeZeroSumSublists(ListNode head) {

        if(head == null){
            return null;
        }
        //遍历
        while(head != null){
            //跳过前面为0的
            if(head.val == 0){
                head = head.next;
                continue;
            }
            Map<Integer,ListNode> map = new HashMap<>();
            int sum = 0;
            ListNode cur = head;
            while(cur != null){
                sum += cur.val;
                if(sum == 0){
                    //如-3 3 0 0 1
                    head = cur.next;
                    break;
                }else if(map.containsKey(sum)){
                    ///1 2 3 -3 4
                    ///1 3 6  3 7 
                    //当map当中的key重复时,代表有加减为0的两个或多个数
                    ListNode pre = map.get(sum);
                    pre.next = cur.next;
                    break;
                }else{
                    //如:1 2 3 4 5 当没有为和为0的
                    map.put(sum,cur);
                }
                cur = cur.next;
            }
            if (cur == null){
                //当遍历完发现没有和为0的直接返回头节点
                return  head;
            }
        }
        return null;
    }
}